package jp.heartdokyun.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import jp.heartdokyun.R;
import jp.heartdokyun.listener.GoBackListener;
import jp.heartdokyun.listener.TopBackListener;
import jp.heartdokyun.util.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewCardActivity extends Activity {

	/** Called when the activity is first created. */
	private MediaPlayer mMediaPlayer;
	private int mImagePos;
	private ImageView ivViewCard;
	private ArrayList<Integer> mListImageIDs;
	private ArrayList<String> mListTitles;
	private ImageButton mIBNext, mIBPrev;
	private TextView mtvTitle;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
		setContentView(R.layout.view_card);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		mListImageIDs = getIntent().getIntegerArrayListExtra("LIST_IMAGE_IDS");
		mListTitles = getIntent().getStringArrayListExtra("LIST_CARD_TITLES");
		mImagePos = getIntent().getExtras().getInt("IMAGE_POSITION", 0);

		ivViewCard = (ImageView) findViewById(R.id.iv_view_card);
		ivViewCard.setImageResource(mListImageIDs.get(mImagePos));
		
		ivViewCard.setOnLongClickListener(new View.OnLongClickListener() { 
			@Override
	        public boolean onLongClick(View v) {
				if (!getResources().getResourceName(
						mListImageIDs.get(mImagePos)).equals(
						"jp.heartdokyun:drawable/noimagel")) {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							ViewCardActivity.this);
					builder.setMessage(
							getString(R.string.dialog_image_download))
							.setCancelable(false)
							.setPositiveButton(getString(R.string.dialog_yes),
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											String fileName = getResources()
													.getResourceName(
															mListImageIDs
																	.get(mImagePos));
											fileName = fileName.substring(24,
													fileName.length());

											File file = new File(
													Environment
															.getExternalStorageDirectory()
															.toString()
															+ "/NaruseKokomi/");
											if (!file.exists()) {
												file.mkdirs();

											}
											File fileImg = new File(
													Environment
															.getExternalStorageDirectory()
															.toString()
															+ "/NaruseKokomi/"
															+ fileName + ".jpg");
											if (!fileImg.exists()) {
												Bitmap image_saved = BitmapFactory
														.decodeResource(
																getResources(),
																mListImageIDs
																		.get(mImagePos));

												FileOutputStream fOut = null;
												try {
													fOut = new FileOutputStream(
															Environment
																	.getExternalStorageDirectory()
																	.toString()
																	+ "/NaruseKokomi/"
																	+ fileName
																	+ ".jpg");
												} catch (FileNotFoundException e) {
													// TODO Auto-generated catch
													// block
													e.printStackTrace();
												}
												image_saved
														.compress(
																Bitmap.CompressFormat.PNG,
																100, fOut);
												try {
													fOut.flush();
													fOut.close();
												} catch (IOException e) {
													// TODO Auto-generated catch
													// block
													e.printStackTrace();
												}
											}

											//finish();
											Toast.makeText(ViewCardActivity.this, R.string.message_image_downloaded,Toast.LENGTH_SHORT).show();
										}
									})
							.setNegativeButton(getString(R.string.dialog_no),
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alert = builder.create();
					alert.show();
				}
				
	            return true;
	        }
	    });


		mtvTitle = (TextView) findViewById(R.id.tv_view_card_title);
		mtvTitle.setText(mListTitles.get(mImagePos));

		ImageButton ibBack = (ImageButton) findViewById(R.id.ib_view_card_back);
		ibBack.setOnClickListener(new GoBackListener(this));

		mIBNext = (ImageButton) findViewById(R.id.btn_next_image);
		mIBNext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mImagePos != mListImageIDs.size() - 1) {
					mImagePos++;
					ivViewCard.setImageResource(mListImageIDs.get(mImagePos));
					mtvTitle.setText(mListTitles.get(mImagePos));
					setVisible();
				}
			}
		});
		mIBPrev = (ImageButton) findViewById(R.id.btn_prev_image);
		mIBPrev.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mImagePos != 0) {
					mImagePos--;
					ivViewCard.setImageResource(mListImageIDs.get(mImagePos));
					mtvTitle.setText(mListTitles.get(mImagePos));
					setVisible();
				}
			}
		});
		// if(imageID==0){
		// btnPrevImg.setVisibility(View.INVISIBLE);
		// }
		// if(imageID==imageMaxID){
		// btnNextImg.setVisibility(View.INVISIBLE);
		// }
		// btnPrevImg.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// imageID--;
		// ivViewCard.setImageResource(imageID);
		// }
		// });
		setVisible();
		ImageButton ibo = (ImageButton) findViewById(R.id.ic_o);
		ibo.setOnClickListener(new TopBackListener(this));

		// mMediaPlayer = MediaPlayer.create(this, R.raw.other_bgm);
		// try {
		// mMediaPlayer = MediaPlayer.create(getApplicationContext(),
		// R.raw.other_bgm);
		// mMediaPlayer.setLooping(true);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }

		mMediaPlayer = new MediaPlayer();
		AssetFileDescriptor afd = getResources().openRawResourceFd(
				R.raw.other_bgm);
		try {
			mMediaPlayer.setDataSource(afd.getFileDescriptor(),
					afd.getStartOffset(), afd.getDeclaredLength());
			mMediaPlayer.prepare();
			float volume = Utils.getBGMVolume(getApplicationContext());
			mMediaPlayer.setVolume(volume, volume);
			// OnCompletionListener listener = null;
			// mMediaPlayer.setOnCompletionListener(listener);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mMediaPlayer.setLooping(true);

		// mMediaPlayer = new MediaPlayer();
		//
		// try {
		// mMediaPlayer.setDataSource(getApplicationContext(),
		// Uri.parse("android.resource://jp.heartdokyun/raw/other_bgm"));
		// } catch (IllegalArgumentException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (SecurityException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (IllegalStateException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// mMediaPlayer.setLooping(true);

	}

	private void setVisible() {
		if (mImagePos == 0)
			mIBPrev.setVisibility(View.INVISIBLE);
		else
			mIBPrev.setVisibility(View.VISIBLE);
		if (mImagePos == mListImageIDs.size() - 1)
			mIBNext.setVisibility(View.INVISIBLE);
		else
			mIBNext.setVisibility(View.VISIBLE);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return false;
	}

	@Override
	public void onDestroy() {
		mMediaPlayer.release();
		super.onDestroy();
	}

	@Override
	public void onResume() {
		if (MainActivity.isEnableBGM) {
			mMediaPlayer.start();
		} else {
			if (mMediaPlayer.isPlaying()) {
				mMediaPlayer.pause();
				mMediaPlayer.seekTo(0);
			}
		}
		super.onResume();
	}

	@Override
	public void onPause() {
		if (mMediaPlayer.isPlaying()) {
			mMediaPlayer.pause();
			mMediaPlayer.seekTo(0);
		}
		mMediaPlayer.release();
		super.onPause();
	}

	// private String getTitlefromLevel(int imageId) {
	// String title = "";
	// for (Level lv : Utils.getDataObj()) {
	// if (lv.getLevel().equals(Integer.toString(imageId))) {
	// title = getResources().getString(R.string.game_tilte)
	// + " "
	// + getString(getResources().getIdentifier(
	// "title_" + lv.getType(), "string",
	// "jp.heartdokyun")) + " Lv." + lv.getLevel();
	// }
	// }
	// return title;
	// }
}